package org.mayuanxiaonong.timserver;

import org.mayuanxiaonong.timserver.codec.msgpack.MessagePackDecoder;
import org.mayuanxiaonong.timserver.codec.msgpack.MessagePackEncoder;
import org.mayuanxiaonong.timserver.handler.ServerHandler;
import org.mayuanxiaonong.timserver.pack.msgpack.IPack;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.ssl.SslContext;

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
	
	private SslContext sslCtx;
	
	public ServerInitializer(SslContext sslCtx) {
		this.sslCtx = sslCtx;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast(sslCtx.newHandler(ch.alloc()));
		// 添加解码器
		pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, IPack.HEAD_LENGTH_OFFSET, IPack.HEAD_LENGTH_LEN));
		pipeline.addLast(new MessagePackDecoder());
		// 添加编码器
		pipeline.addLast(new LengthFieldPrepender(IPack.HEAD_LENGTH_LEN));
		pipeline.addLast(new MessagePackEncoder());
		// 添加业务处理器
		pipeline.addLast(new ServerHandler());
	}

}
